package com.example.casper.Experiment2024.data;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;
import com.example.casper.Experiment2024.R;
import com.example.casper.Experiment2024.TravelRecordsFragment;
import com.tencent.map.lib.thread.AsyncTask;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

public class RecordsDetailsActivity extends AppCompatActivity implements LocationListener {
    private ViewPager2 viewPager;
    private ImageAdapter imageAdapter;
    private ArrayList<Uri> imageUris = new ArrayList<>();
    private static final int REQUEST_CODE_PICK_IMAGE = 100;
    private LocationManager locationManager;
    private static final String SK = "1j4VyyffUc37dzapJV9ktfOF3HaiGuUd"; // 替换为你的SecretKey
    private static final String API_KEY = "QVLBZ-OAFCA-SBBKO-CSXNC-O4NJZ-AOF4B"; // 替换为你的APIKey
    private static final String GEOCODER_URL = "https://apis.map.qq.com/ws/geocoder/v1";


    @SuppressLint("NotifyDataSetChanged")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_records_details);

        EditText latitudeEditText = findViewById(R.id.latitudeTextText);
        EditText longitudeEditText = findViewById(R.id.longitudeTextText);
        Button locateButton = findViewById(R.id.Locatebutton);
        // 获取位置管理器
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // 检查是否具有位置权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // 请求位置权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
            return;
        }
        // 请求位置更新
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        locateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取最后已知的位置
                if (ActivityCompat.checkSelfPermission(RecordsDetailsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(RecordsDetailsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    // 权限已经被授予，可以安全地调用getLastKnownLocation
                    if(!latitudeEditText.getText().toString().isEmpty())
                    {
                        FetchLocation(latitudeEditText.getText().toString(), longitudeEditText.getText().toString());
                        return;
                    }
                    Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (lastKnownLocation != null) {
                        // 获取经纬度
                        double latitude = lastKnownLocation.getLatitude();
                        double longitude = lastKnownLocation.getLongitude();
                        FetchLocation(String.valueOf(latitude), String.valueOf(longitude));
                        // 更新EditText
                        latitudeEditText.setText(String.valueOf(latitude));
                        longitudeEditText.setText(String.valueOf(longitude));
                    } else {
                        // 如果无法获取最后已知的位置，可以提示用户
                        latitudeEditText.setText(R.string.unknown);
                        longitudeEditText.setText(R.string.unknown);
                    }
                }else{                        // 如果无法获取最后已知的位置，可以提示用户
                    latitudeEditText.setText(R.string.unknown);
                    longitudeEditText.setText(R.string.unknown);}
            }
        });

        Button RecordsButton = findViewById(R.id.Record_Button);
        viewPager = findViewById(R.id.viewPager);
        Button uploadButton = findViewById(R.id.Upload_Button);
        // 初始化适配器
        imageAdapter = new ImageAdapter(imageUris);
        viewPager.setAdapter(imageAdapter);
        // 设置上传按钮的点击事件
        uploadButton.setOnClickListener(v -> openImagePicker());
        //图片删除功能实现
        Button deleteButton = findViewById(R.id.Delete_Button);
        deleteButton.setOnClickListener(v -> {
            int currentPosition = viewPager.getCurrentItem();
            if (!imageUris.isEmpty() && currentPosition >= 0 && currentPosition < imageUris.size()) {
                imageUris.remove(currentPosition);
                imageAdapter.notifyItemRemoved(currentPosition);
                imageAdapter.notifyItemRangeChanged(currentPosition, imageUris.size());
            }
        });

        Intent intent = getIntent();
        if (intent != null) {
            // 从Intent中获取传递的数据ArrayList<String> ImageUriString = intent.getStringArrayListExtra("photo");
            ArrayList<String> ImageUriString = intent.getStringArrayListExtra("photo");
            if (ImageUriString != null) {
                for (String uriString : ImageUriString) {
                    imageUris.add(Uri.parse(uriString));
                }
                imageAdapter.notifyDataSetChanged();
            }
            String title = intent.getStringExtra("Title");
            if (null != title) {
                String text = intent.getStringExtra("description");
                EditText recordtitle= findViewById(R.id.Records_Title_Text);
                recordtitle.setText(title);
                EditText recordtext= findViewById(R.id.editText);
                recordtext.setText(text);
                EditText recordlocationname=findViewById(R.id.Locationname);
                recordlocationname.setText(intent.getStringExtra("locationname"));
                latitudeEditText.setText(String.valueOf(intent.getDoubleExtra("latitude",116.397477)));
                longitudeEditText.setText(String.valueOf(intent.getDoubleExtra("longitude",39.908692)));
            }
        }
        RecordsButton.setOnClickListener(v -> {
            Intent returnintent = new Intent();
            ArrayList<String> uriStrings = new ArrayList<>();
            assert intent != null;
            if (!imageUris.isEmpty()) {
                // 将每个 Uri 转换为字符串并存储在数组中
                for (int i = 0; i < imageUris.size(); i++) {
                    uriStrings.add(imageUris.get(i).toString());
                }
            }
            EditText recordtitle= findViewById(R.id.Records_Title_Text);
            EditText recordtext= findViewById(R.id.editText);
            EditText recordlocationname=findViewById(R.id.Locationname);
            String tourview=recordtext.getText().toString();
            if(recordtitle.getText().toString().isEmpty()||recordtext.getText().toString().isEmpty()||recordlocationname.getText().toString().isEmpty()||uriStrings.isEmpty())
            {
                Toast.makeText(RecordsDetailsActivity.this, "不能有内容为空", Toast.LENGTH_LONG).show();
                return;
            }
            returnintent.putExtra("Title", recordtitle.getText().toString());
            returnintent.putStringArrayListExtra("photo", uriStrings);
            returnintent.putExtra("position",intent.getIntExtra("position",0));
            returnintent.putExtra("description",tourview);
            returnintent.putExtra("locationname",recordlocationname.getText().toString());
            returnintent.putExtra("latitude",Double.parseDouble(latitudeEditText.getText().toString()));
            returnintent.putExtra("longitude",Double.parseDouble(longitudeEditText.getText().toString()));
            setResult(Activity.RESULT_OK, returnintent);
            RecordsDetailsActivity.this.finish();
        });
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
    }

    public void FetchLocation(String latitude, String longitude) {
        new FetchAddressTask().execute(latitude, longitude);
    }

    public static class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {

        private final ArrayList<Uri> imageUris;

        public ImageAdapter(ArrayList<Uri> imageUris) {
            this.imageUris = imageUris;
        }
        @NonNull
        @Override
        public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.records_image_layout, parent, false);
            return new ImageViewHolder(view);
        }
        @Override
        public void onBindViewHolder(@NonNull ImageViewHolder holder, int position) {
            boolean contains = imageUris.get(position).toString().matches("^\\d+$");
            if(contains)
            {
                holder.imageView.setImageResource(Integer.parseInt(String.valueOf(imageUris.get(position))));
            }
            else holder.imageView.setImageURI(imageUris.get(position));
        }
        @Override
        public int getItemCount() {
            return imageUris.size();
        }
        static class ImageViewHolder extends RecyclerView.ViewHolder {
            ImageView imageView;

            public ImageViewHolder(@NonNull View itemView) {
                super(itemView);
                imageView = itemView.findViewById(R.id.imageView);
            }
        }
    }
    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); // 如果支持多选
        startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == RESULT_OK) {
            if (data != null) {
                ClipData clipData = data.getClipData();
                if (clipData != null) {
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        Uri imageUri = clipData.getItemAt(i).getUri();
                        getContentResolver().takePersistableUriPermission(
                                imageUri,
                                Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                        );
                        imageUris.add(imageUri);
                    }
                    imageAdapter.notifyDataSetChanged();
                } else if (data.getData() != null) {
                    Uri imageUri = data.getData();
                    getContentResolver().takePersistableUriPermission(
                            imageUri,
                            Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                    );
                    imageUris.add(imageUri);
                    imageAdapter.notifyItemInserted(imageUris.size() - 1);
                }
            }
        }
    }


    @Override
    public void onLocationChanged(@NonNull Location location) {
    }

    @Override
    public void onLocationChanged(@NonNull List<Location> locations) {
        LocationListener.super.onLocationChanged(locations);
    }

    @Override
    public void onFlushComplete(int requestCode) {
        LocationListener.super.onFlushComplete(requestCode);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        LocationListener.super.onStatusChanged(provider, status, extras);
    }

    @Override
    public void onProviderEnabled(@NonNull String provider) {
        LocationListener.super.onProviderEnabled(provider);
    }

    @Override
    public void onProviderDisabled(@NonNull String provider) {
        LocationListener.super.onProviderDisabled(provider);
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        super.onPointerCaptureChanged(hasCapture);
    }
    public class FetchAddressTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            String latitude = params[0];
            String longitude = params[1];

            try {
                String sig = generateSignature(latitude, longitude);
                String url = GEOCODER_URL + "?location=" + latitude + "," + longitude + "&key=" + API_KEY + "&sig=" + sig;

                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                connection.setRequestMethod("GET");
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                return response.toString();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            if (result != null) {
                try {
                    JSONObject json = new JSONObject(result);
                    JSONObject formattedAddresses = json.getJSONObject("result").getJSONObject("formatted_addresses");
                    String address = formattedAddresses.getString("standard_address")+formattedAddresses.getString("recommend");
                    //Toast.makeText(RecordsDetailsActivity.this, "Address: " + address, Toast.LENGTH_LONG).show();
                    EditText addressTextView=findViewById(R.id.Locationname);
                    addressTextView.setText(address);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(RecordsDetailsActivity.this, "Failed to fetch address", Toast.LENGTH_LONG).show();
                }
            } else {
                Toast.makeText(RecordsDetailsActivity.this, "Failed to fetch address", Toast.LENGTH_LONG).show();
            }
        }
    }

    private String generateSignature(String latitude, String longitude) throws NoSuchAlgorithmException {
        String originalString = "/ws/geocoder/v1?key=" + API_KEY + "&location=" + latitude + "," + longitude + SK;
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digest = md.digest(originalString.getBytes());
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}